# -*- codung: utf-8 -*-
import re
import urllib

import simplejson as json



class UrlOpener(urllib.FancyURLopener):
	version = "py-gtranslate/1.0"

class InvalidLanguage(Exception): pass

base_uri = "http://ajax.googleapis.com/ajax/services/language/translate"
default_params = {'v': '1.0'}

def translate(src, to, phrase):	
	args = default_params.copy()
	args.update({
		'langpair': '%s%%7C%s' % (src, to),
		'q': urllib.quote_plus(phrase),
	})
	argstring = '%s' % ('&'.join(['%s=%s' % (k,v) for (k,v) in args.iteritems()]))
	text=UrlOpener().open('%s?%s' % (base_uri, argstring)).read()
	print(text)
	resp = json.loads(text)
	try:
		return resp['responseData']['translatedText']
	except:
		# should probably warn about failed translation
		return phrase





	
	
